package com.sunseen.capacitormachine.modules.parameter.productparameter.edit;

import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.widget.Toast;

import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.format.selected.BaseSelectFormat;
import com.bin.david.form.data.table.FormTableData;
import com.bin.david.form.data.table.TableData;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.common.Form;
import com.sunseen.capacitormachine.databinding.FragmentEditAgingParameterBinding;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.modules.parameter.productivetask.event.SetParameterEvent;

import androidx.databinding.ViewDataBinding;

import org.greenrobot.eventbus.EventBus;

/**
 * @author zest
 */
public class EditAgingParameterFragment extends BaseFragment {


    private Form selectForm;
    private int curCol = -1;
    private int curRow = -1;

    @Override
    protected int setLayout() {
        return R.layout.fragment_edit_aging_parameter;
    }

    private TextWatcher textWatcher1;

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        final FragmentEditAgingParameterBinding binding = (FragmentEditAgingParameterBinding) viewDataBinding;

        Form[][] measureForm = new Form[][]{
                {
                        new Form(getString(R.string.aging_duration)),
                        new Form(getString(R.string.minute), 10)
                },
                {
                        new Form(getString(R.string.instrument_frequency)),
                        new Form("120Hz", 10)
                },
                {
                        new Form(getString(R.string.oven_temperature)),
                        new Form(getString(R.string.temp_unit_flag), 10)
                },
                {
                        new Form(getString(R.string.feed_in_table_height)),
                        new Form("(单位:脉冲)", 10)
                },
                {
                        new Form(getString(R.string.feed_in_angle)),
                        new Form("(单位:度)", 10)
                },
                {
                        new Form(getString(R.string.discharge_angle)),
                        new Form("(单位:度)", 10)
                },
                {
                        new Form(getString(R.string.discharge_table_height)),
                        new Form("(单位:脉冲)", 10)
                },

        };

        textWatcher1 = new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString();
                if (str.contains(".")) {
                    int pointIndex = str.indexOf(".");
                    if (str.length() - pointIndex > 2) {
                        binding.editInput.setText(str.substring(0, pointIndex + 2));
                    }
                }
            }
        };
        FormTableData<Form> formData = FormTableData.create(binding.table,
                "", 11, measureForm);
        formData.setFormat((t) -> {
            if (t != null) {
                return t.getContent();
            } else {
                return "";
            }
        });
        formData.setOnItemClickListener(new TableData.OnItemClickListener<Form>() {
            @Override
            public void onClick(Column column, String value, Form form, int col, int row) {
                if (col == 1) {
                    curCol = col;
                    curRow = row;
                    selectForm = form;
                    binding.btnInput.setEnabled(true);
                    binding.editInput.setText("");
                    if (row == 4 || row == 5) {
                        binding.editInput.setKeyListener(new DigitsKeyListener(true, true));
                        binding.editInput.removeTextChangedListener(textWatcher1);
                        binding.editInput.addTextChangedListener(textWatcher1);
                    } else if (row == 1) {
                        binding.editInput.setKeyListener(new DigitsKeyListener(false, false));
                        binding.editInput.removeTextChangedListener(textWatcher1);
                    } else {
                        binding.editInput.setKeyListener(new DigitsKeyListener(false, true));
                        binding.editInput.removeTextChangedListener(textWatcher1);
                        binding.editInput.addTextChangedListener(textWatcher1);
                    }
                } else {
                    binding.btnInput.setEnabled(false);
                }
            }
        });
        binding.table.getConfig().setShowXSequence(false);
        binding.table.getConfig().setShowYSequence(false);
        binding.table.getConfig().setShowTableTitle(false);
        binding.table.getConfig().getContentGridStyle()
                .setColor(getResources().getColor(R.color.table_content_grid_color));
        binding.table.getConfig().getContentStyle()
                .setTextColor(getResources().getColor(R.color.table_content_text_color));
        binding.table.setSelectFormat(new BaseSelectFormat());
        binding.table.setTableData(formData);
        binding.editInput.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString();
                if (str.contains(".")) {
                    int pointIndex = str.indexOf(".");
                    if (str.length() - pointIndex > 2) {
                        binding.editInput.setText(str.substring(0, pointIndex + 2));
                    }
                }
            }
        });
        binding.btnInput.setOnClickListener((view) -> {
            if (curCol == 1) {
                String content = binding.editInput.getText().toString();
                //用户未输入，或只输入了一个小数点，不做处理，提示用户输入错误
                if (content.length() == 0 || (content.length() == 1 && ".".equals(content))) {
                    Toast.makeText(_mActivity, getString(R.string.number_input_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                switch (curRow) {
                    case 0: {
                        EventBus.getDefault().post(new SetParameterEvent(true, "agingTime", content));
                        selectForm.setContent(content + getString(R.string.minute));
                        binding.table.invalidate();
                    }
                    break;
                    case 1: {
//                        selectForm.setContent(content + getString(R.string.hz));
//                        binding.table.invalidate();
//                        parameter.setInstrumentFrequency(Integer.valueOf(content));
                        Toast.makeText(_mActivity, "仪表频率固定120Hz", Toast.LENGTH_SHORT).show();
                    }
                    break;
                    case 2: {
                        int ovenTemperature = (int) (Float.valueOf(content) * 10);
                        EventBus.getDefault().post(new SetParameterEvent(true,
                                "ovenTemperature", ovenTemperature));
                        selectForm.setContent(content + getString(R.string.temp_unit_flag));
                        binding.table.invalidate();
                    }
                    break;
                    case 3: {
                        int value = (int) (Float.valueOf(content) * 10);
                        if (heightValid(value)) {
                            selectForm.setContent(content);
                            binding.table.invalidate();
                            EventBus.getDefault().post(new SetParameterEvent(true, "feedInTableHeight", value));
                        } else {
                            Toast.makeText(_mActivity, getString(R.string.height_invalid_tip), Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                    case 4: {
                        int value = (int) (Float.valueOf(content) * 10);
                        if (angleValid(value)) {
                            selectForm.setContent(content);
                            binding.table.invalidate();
                            //value += 1800;
                            EventBus.getDefault().post(new SetParameterEvent(true, "feedInAngle", value));
                        } else {
                            //Toast.makeText(_mActivity, getString(R.string.angle_invalid_tip), Toast.LENGTH_SHORT).show();
                            Toast.makeText(_mActivity, getString(R.string.angle_invalid_tip1), Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                    case 5: {
                        int value = (int) (Float.valueOf(content) * 10);
                        if (angleValid(value)) {
                            selectForm.setContent(content);
                            binding.table.invalidate();
                            //value += 1800;
                            EventBus.getDefault().post(new SetParameterEvent(true, "dischargeAngle", value));
                        } else {
//                            Toast.makeText(_mActivity, getString(R.string.angle_invalid_tip), Toast.LENGTH_SHORT).show();
                            Toast.makeText(_mActivity, getString(R.string.angle_invalid_tip1), Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                    case 6: {
                        int value = (int) (Float.valueOf(content) * 10);
                        if (heightValid(value)) {
                            selectForm.setContent(content);
                            binding.table.invalidate();
                            EventBus.getDefault().post(new SetParameterEvent(true, "dischargeTableHeight", value));
                        } else {
                            Toast.makeText(_mActivity, getString(R.string.height_invalid_tip), Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
            }
        });
    }


    private boolean angleValid(int value) {
        return value >= -1800 && value <= 1800;
    }

    private boolean heightValid(int value) {
        return value >= 0 && value <= 10000;
    }
}
